package com.gitee.es.dynamics.util;

import com.gitee.es.dynamics.common.Const;
import com.gitee.es.dynamics.common.ElasticSearchConfig;
import com.gitee.es.dynamics.common.LocalCache;
import com.gitee.es.dynamics.exception.DynamicsElasticSearchException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

import java.util.List;

@Slf4j
public class CoreUtil {
    /**
     * 加载数据源核心配置
     *
     * @param list es数据源配置
     * @return void
     * @date 2023/12/29 8:42
     * @author glq
     */
    public static void loadCoreConfig(List<ElasticSearchConfig> list) {
        if (list == null || list.size() == 0) {
            throw new DynamicsElasticSearchException("load error,config must not be null!");
        }
        log.info("Dynamics elasticSearch config start");
        list.forEach(elasticSearchConfig -> {
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticSearchConfig.getUsername(), elasticSearchConfig.getPassword()));
            RestClientBuilder builder = RestClient.builder(new HttpHost(elasticSearchConfig.getHost(), elasticSearchConfig.getPort()))
                    .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
            LocalCache.put(Const.BEAN_PREFIX1 + elasticSearchConfig.getRoute(), new ElasticsearchRestTemplate(new RestHighLevelClient(builder)));
            log.info("Load " + elasticSearchConfig.getRoute() + " elasticSearch config success");
        });
        log.info("Load dynamics elasticSearch config complete!");

    }

    /**
     * 清除数据源核心配置
     *
     * @return void
     * @date 2023/12/29 9:00
     * @author glq
     */
    public static void clearCoreConfig() {
        LocalCache.removeByKeyPrefix(Const.BEAN_PREFIX1);
    }
}
